package binarytree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/18 22:14
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * 给你二叉树的根节点 root ，返回其节点值的 层序遍历 。 （即逐层地，从左到右访问所有节点）。
 */
public class LevelOrder {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 层次遍历 队列
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<TreeNode> levelNodes = new LinkedList<>();
        if (root != null) {
            levelNodes.add(root);
        }
        while (!levelNodes.isEmpty()) {
            List<Integer> temp = new ArrayList<>();
            int size = levelNodes.size();
            while (size > 0) {
                //遍历一层上的每个节点
                TreeNode node = levelNodes.poll();
                temp.add(node.val);
                size--;
                if (node.left != null) {
                    levelNodes.offer(node.left);
                }
                if (node.right != null) {
                    levelNodes.offer(node.right);
                }
            }
            result.add(temp);
        }
        return result;
    }


    /**
     * 层序遍历 DFS递归
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        dfsSearing(root, 0, result);
        return result;
    }

    public void dfsSearing(TreeNode root, int deep, List<List<Integer>> result) {
        if (root == null) {
            return;
        }
        deep++;
        //代表本层没有创建List<Integer>（即，当前深度没有遍历到本层的任何一个节点时，创建）
        if (result.size() < deep) {
            List<Integer> temp = new ArrayList<>();
            result.add(temp);
        }
        result.get(deep - 1).add(root.val);
        dfsSearing(root.left, deep, result);
        dfsSearing(root.right, deep, result);
    }

    public static void main(String[] args) {

    }
}
